/* eslint-disable array-callback-return */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined, LinkOutlined, PlusCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, Input, Select, Tooltip, message, Modal, Spin } from 'antd';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import Policy from '../../components/PolicyDetail';
import Customer from '../../components/Customer';
import Area from '../../components/Area';

import BankForm from './Bank';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ singlemanage, loading }) => ({
  loading: loading.models.singlemanage || loading.models.publicdata,
  formFieldsValue: singlemanage.formFieldsValue,
  expandForm: singlemanage.expandForm,
  pageData: singlemanage.pageData,
  activeKey: singlemanage.activeKey,
}))
@Form.create()
class AdvancedForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      custId: '', // 客户名称id
      payWayList: [], // 支付方式字典数据
      payWay: '3', // 支付方式
      fundList: [], // 公积金组合列表数据
      bankAccoList: [], // 下拉列表中客户银行账户信息
      bankList: [], // 银行列表字典数据
      yesNoList: [], // 是否可突破上线字典数据
      YES_NO_FLAG: [], // 是否开户完成字典数据
      policyVisible: 'false', // 政策弹框变量
      updateModVisible: 'false', // 新增银行弹框变量
      plcyId: '', // 公积金组合id
      accuOrIns: '2', // 社保传1 ， 公积金传2
      subFlg: false,
      mdCustId: '',
      isdoneFlag: '1', // 是否开户完成
      corpProp: null,
      empProp: null,
    };
  }

  componentDidMount() {
    // 获取页面所有的字典值
    const { dispatch } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['ACCO_PAY_WAY', 'BANK_ID', 'PAY_FEES_WAY', 'YES_NO_FLAG'],
    }).then(data => {
      if (data && data.ACCO_PAY_WAY && data.ACCO_PAY_WAY.length) {
        this.setState({ payWayList: data.ACCO_PAY_WAY });
      }
      if (data && data.BANK_ID && data.BANK_ID.length) {
        this.setState({ bankList: data.BANK_ID });
      }
      if (data && data.YES_NO_FLAG && data.YES_NO_FLAG.length) {
        this.setState({ yesNoList: data.YES_NO_FLAG, YES_NO_FLAG: data.YES_NO_FLAG });
      }
      if (data && data.PAY_FEES_WAY && data.PAY_FEES_WAY.length) {
        data.PAY_FEES_WAY.forEach(item => {
          if (item.itemName === '单立户') {
            this.setState({ payWay: item.itemCode });
          }
        });
      }
    });
  }

  // 模糊查询 (客户名称)
  getData = value => {
    const { dispatch, form } = this.props;
    const { bankList } = this.state;
    this.setState({ custId: value });
    form.resetFields(['custBankId']); // 重置上一次带出的银行账户信息
    // 获取统一社会信用代码数据
    dispatch({
      type: 'singlemanage/getUniCreditCode',
      payload: {
        custId: value,
      },
    }).then(response => {
      if (response.success && response.data) {
        form.setFieldsValue({ uniCreditCode: response.data.uniCreditCode });
        this.setState({ mdCustId: response.data.mdCustId });
      } else {
        message.warning(response.message || '获取统一社会信用代码失败：服务器端错误');
      }
    });
    // 获取银行账户信息数据
    dispatch({
      type: 'singlemanage/getBankAccoList',
      payload: {
        custId: value,
      },
    }).then(response => {
      if (response.success && response.data && response.data.length) {
        const bankAccoList = [];
        response.data.map(item => {
          const temp = item;
          temp.bankId = this.matchDict(bankList, item.bankId);
          const bankInfo = `${item.bankId} ${item.bankAcco}`;
          const { bankAccoId } = item;
          bankAccoList.push({ bankAccoId, bankInfo });
        });
        this.setState({ bankAccoList });
      }
    });
  };

  // 模糊查询 (地区)
  getAreaData = value => {
    const { dispatch, form } = this.props;
    const { payWay } = this.state;
    this.setState({ plcyId: '' });
    form.resetFields(['plcyId']); //  重置上一次带出的公积金组合id
    dispatch({
      type: 'singlemanage/getAccuLsPkgName',
      payload: {
        payWay,
        areaId: value.key,
      },
    }).then(response => {
      if (response.success && response.data && response.data.length) {
        this.setState({ fundList: response.data });
      } else {
        this.setState({ fundList: [] });
      }
    });
    dispatch({
      type: 'singlemanage/getQueryPlcyParam',
      payload: {
        areaId: value.key,
      },
    }).then(response => {
      if (response.success) {
        form.resetFields(['doneFlag']);
        // eslint-disable-next-line no-empty
        if (response.success && response.data.areaId) {
        } else {
          message.warning('根据地区获取不到是否五险合一规则，请联系平台管理员配置。');
        }
      } else {
        form.resetFields(['doneFlag']);
      }
    });
  };

  // 匹配字典
  matchDict = (list, id) => {
    let dict = null;
    list.map(item => {
      if (Number(item.itemCode) === id) {
        dict = item.itemName;
      }
    });
    return dict;
  };

  // 选中支付方式
  selectPayWay = value => {
    this.setState({ payWay: value });
  };

  // 选择是否开户完成
  isdoneFlag = e => {
    this.setState({ isdoneFlag: e });
  };

  // 选择公积金组合
  selectFundGroup = value => {
    const { fundList } = this.state;
    const fundGroup = fundList.filter(item => item.accuLsPkgId === value);
    this.setState({
      corpProp: fundGroup[0].corpProp,
      empProp: fundGroup[0].empProp,
      plcyId: value,
    });
  };

  // 提交
  submitAll = url => {
    const { dispatch, form } = this.props;
    const { corpProp, empProp, mdCustId } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        const temp = values;
        let areaId = null;
        temp.accuComRatioVal = corpProp;
        temp.accuPerRatioVal = empProp;
        if (values.areaId) {
          areaId = values.areaId && values.areaId.key;
          delete temp.areaId;
        }
        const param = {
          ...values,
          mdCustId,
          areaId,
        };
        dispatch({
          type: 'singlemanage/checkBefAccuInsert',
          payload: param,
        }).then(res => {
          if (res.success) {
            if (res.data) {
              confirm({
                icon: <QuestionCircleOutlined />,
                title: '是否继续添加?',
                content: res.data,
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                  let urlName = null;
                  if (url === '/custAccuAcco/insert') {
                    urlName = 'singlemanage/custAccuInsert';
                  } else {
                    urlName = 'singlemanage/custAccuBeginUse';
                  }
                  dispatch({
                    type: urlName,
                    payload: param,
                  }).then(result => {
                    if (result.success) {
                      this.setState({ subFlg: true });
                      message.success('新增成功', 2, () => {
                        dispatch({
                          type: 'singlemanage/updateModelData',
                          payload: {
                            activeKey: '2',
                            formFieldsValue: {}, // 表单域
                            expandForm: false, // 展开收起
                            pageData: {
                              pagination: {
                                current: 1,
                                pageSize: 10,
                                total: 10,
                              },
                            },
                          },
                        });
                        router.push('/customservicemanage/singleaccount/index?activeKey=2');
                      });
                    } else {
                      message.warning(`${result.message || '社保新增失败：服务器端错误'}`);
                    }
                  });
                },
              });
            } else {
              let urlName = null;
              if (url === '/custAccuAcco/insert') {
                urlName = 'singlemanage/custAccuInsert';
              } else {
                urlName = 'singlemanage/custAccuBeginUse';
              }
              dispatch({
                type: urlName,
                payload: param,
              }).then(result => {
                if (result.success) {
                  this.setState({ subFlg: true });
                  message.success('新增成功', 2, () => {
                    dispatch({
                      type: 'singlemanage/updateModelData',
                      payload: {
                        activeKey: '2',
                        formFieldsValue: {}, // 表单域
                        expandForm: false, // 展开收起
                        pageData: {
                          pagination: {
                            current: 1,
                            pageSize: 10,
                            total: 10,
                          },
                        },
                      },
                    });
                    router.push('/customservicemanage/singleaccount/index?activeKey=2');
                  });
                } else {
                  message.warning(`${result.message || '社保新增失败：服务器端错误'}`);
                }
              });
            }
          } else {
            message.warning(res.message || '提交数据失败：服务器端错误');
          }
        });
      }
    });
  };

  // 增加银行
  setModalShow = () => {
    this.setState({ updateModVisible: 'true' });
  };

  // 传给银行子组件的函数
  cancelModal = (modalClose, success) => {
    this.setState({ updateModVisible: modalClose });
    const { dispatch } = this.props;
    const { custId, bankList } = this.state;
    if (success) {
      dispatch({
        type: 'singlemanage/getBankAccoList',
        payload: {
          custId,
        },
      }).then(response => {
        if (response.success && response.data && response.data.length) {
          const bankAccoList = [];
          response.data.map(item => {
            const temp = item;
            temp.bankId = this.matchDict(bankList, item.bankId);
            const bankInfo = `${item.bankId} ${item.bankAcco}`;
            const { bankAccoId } = item;
            bankAccoList.push({ bankAccoId, bankInfo });
          });
          this.setState({ bankAccoList });
        } else {
          message.warning(response.message || '获取银行账户信息失败：服务器端错误');
        }
      });
    }
  };

  // 弹出政策详情
  setPolicyModalShow = () => {
    this.setState({ policyVisible: 'true' });
  };

  // 传给政策子组件的函数
  cancelPolicyModal = modalClose => {
    this.setState({ policyVisible: modalClose });
  };

  // 取消
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'singlemanage/updateModelData',
      payload: {
        activeKey: '2',
        formFieldsValue: {}, // 表单域
        expandForm: false, // 展开收起
        pageData: {
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      },
    });
    router.push('/customservicemanage/singleaccount/index?activeKey=2');
  };

  // 渲染函数
  render() {
    const {
      form: { getFieldDecorator },
      submitting,
      loading,
    } = this.props;
    const {
      payWayList,
      updateModVisible,
      custId,
      bankAccoList,
      yesNoList,
      fundList,
      policyVisible,
      plcyId,
      accuOrIns,
      isdoneFlag,
      YES_NO_FLAG,
      subFlg,
    } = this.state;

    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>公积金账户信息</span>}
              className={styles.card}
              bordered={false}
            >
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="客户名称">
                    {getFieldDecorator('custId', {
                      rules: [{ required: true, message: '请输入' }],
                    })(<Customer getData={this.getData} />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="公积金账户名称">
                    {getFieldDecorator('accoName', {
                      rules: [{ required: true, pattern:/^(?!\.)[^\\/:*?"<>|]{1,255}$/,message: '文件名不能包含下列任何字符  \\  /  :  *   ?  "  <  >  |'}],
                    })(<Input placeholder="请输入" maxLength={100} />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="统一社会信用代码">
                    {getFieldDecorator('uniCreditCode', {
                      rules: [
                        {
                          required: true,
                          message: '长度为18位的数字与字母组合',
                          pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{18}$/,
                        },
                      ],
                    })(<Input placeholder="请输入" disabled />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="地区">
                    {getFieldDecorator('areaId', {
                      rules: [{ required: true, message: '请选择' }],
                    })(<Area onSelect={this.getAreaData} labelInValue />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="单位名称">
                    {getFieldDecorator('orgName', {
                      rules: [{ required: true, message: '请输入' }],
                    })(<Input placeholder="请输入" maxLength={100} />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="所属公积金机构">
                    {getFieldDecorator('accuOrg', {
                      rules: [{ required: true, message: '请输入' }],
                    })(<Input placeholder="请输入" maxLength={100} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="支付方式">
                    {getFieldDecorator('payWay', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <Select placeholder="请选择" onChange={this.selectPayWay}>
                        {payWayList.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="是否可突破上限">
                    {getFieldDecorator('exceedCeilingFlag', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: '2',
                    })(
                      <Select placeholder="请选择">
                        {yesNoList.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <Col span={22} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem label="银行账户信息">
                      {getFieldDecorator('custBankId', {
                        rules: [{ required: false, message: '请输入' }],
                      })(
                        <Select placeholder="请选择">
                          {bankAccoList.map(item => (
                            <Option key={item.bankAccoId}>{item.bankInfo}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} offset={1} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem>
                      {custId ? (
                        <PlusCircleOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: '#40a9ff',
                            fontSize: '24px',
                          }}
                          onClick={this.setModalShow}
                        />
                      ) : (
                        <PlusCircleOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: 'rgb(206, 206, 206)',
                            fontSize: '24px',
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem
                    label={
                      <Tooltip
                        placement="right"
                        title="实际业务情况中该账户未开户完成，可以使用是否开户完成功能进行标记。后续开户完成时，进行修改取消标记即可。针对工伤险种，取消未开户完成标记时，需维护工伤比例信息。"
                      >
                        <span>是否开户完成</span>
                        <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
                      </Tooltip>
                    }
                  >
                    {getFieldDecorator('doneFlag', {
                      rules: [{ required: false, message: '请输入' }],
                      initialValue: isdoneFlag,
                    })(
                      <Select placeholder="请选择" onChange={this.isdoneFlag}>
                        {YES_NO_FLAG.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <Col span={22} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem label="公积金组合">
                      {getFieldDecorator('plcyId', {
                        rules: [{ required: true, message: '请输入' }],
                      })(
                        // <Select placeholder="请选择公积金组合" onSelect={this.selectFundGroup}>
                        //   {fundList.map(item => (
                        //     <Option key={item.accuLsPkgId}>{item.accuLsPkgName}</Option>
                        //   ))}
                        // </Select>
                        <HOCSelect
                          placeholder="请选择"
                          showSearch
                          allowClear
                          optionFilterProp="children"
                          onSelect={this.selectFundGroup}
                        >
                          {fundList.map(item => (
                            <Option key={item.accuLsPkgId}>{item.accuLsPkgName}</Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} offset={1} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem>
                      {plcyId ? (
                        <LinkOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: '#40a9ff',
                            fontSize: '24px',
                          }}
                          onClick={this.setPolicyModalShow}
                        />
                      ) : (
                        <LinkOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: 'rgb(206, 206, 206)',
                            fontSize: '24px',
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="备注">
                    {getFieldDecorator('remark', {})(
                      <Input placeholder="请输入" maxLength={200} />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            {updateModVisible === 'true' ? (
              <BankForm custId={custId} cancelModal={this.cancelModal} />
            ) : null}
            {policyVisible === 'true' ? (
              <Policy
                plcyId={plcyId}
                accuOrIns={accuOrIns}
                cancelPolicyModal={this.cancelPolicyModal}
              />
            ) : null}
            <FooterToolbar style={{ width: '100%' }}>
              <Button onClick={this.cancel} style={{ marginRight: 10 }}>
                取消
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.submitAll('/custAccuAcco/insert');
                }}
                loading={submitting}
                disabled={subFlg}
              >
                提交
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.submitAll('/custAccuAcco/insertAndBeginUse');
                }}
                loading={submitting}
                disabled={subFlg}
              >
                提交并启用
              </Button>
            </FooterToolbar>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AdvancedForm;
